﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using SpringStudio.Common;
using SpringStudio.DAL;

namespace Sdepci.InfoCode.BLL.CodeIndex
{
    /// <summary>
    /// 编码字典管理类
    /// </summary>
    public class DictManager
    {
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="parentDictGuid">父节点</param>
        /// <param name="cateGuid">索引Guid</param>
        /// <param name="dictCode">字典代码</param>
        /// <param name="dictText">字典文本</param>
        /// <param name="dictDesc">中文描述</param>
        /// <param name="seq">显示次序</param>
        /// <returns>是否成功</returns>
        public bool Add(string parentDictGuid, string cateGuid, string dictCode, string dictText, string dictDesc, int seq)
        {
            try
            {
                string sql = string.Empty;
                string dictGuid = Guid.NewGuid().ToString(); // 创建一个新的Guid
                sql = "Insert Into InfoCodeDicts (DictGuid,ParentDictGuid,CateGuid,DictCode,DictText,DictDesc,Seq) Values(@DictGuid,@ParentDictGuid,@CateGuid,@DictCode,@DictText,@DictDesc,@Seq)";
                SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@DictGuid", dictGuid),
                    SqlHelper.NewSqlParameter("@ParentDictGuid", parentDictGuid),
                    SqlHelper.NewSqlParameter("@CateGuid", cateGuid),
                    SqlHelper.NewSqlParameter("@DictCode", dictCode),
                    SqlHelper.NewSqlParameter("@DictText", dictText),
                    SqlHelper.NewSqlParameter("@DictDesc", dictDesc),
                    SqlHelper.NewSqlParameter("@Seq", seq));

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="dictGuid">索引字典ID</param>
        /// <returns>是否成功</returns>
        public bool Delete(string dictGuid)
        {
            try
            {
                string sql = string.Empty;
                sql = "Delete From InfoCodeDicts Where DictGuid=@DictGuid";
                SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@DictGuid", dictGuid));

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dictGuid">字典ID</param>
        /// <param name="dictCode">字典代码</param>
        /// <param name="dictText">字典文本</param>
        /// <param name="dictDesc">中文描述</param>
        /// <param name="seq">显示次序</param>
        /// <returns>是否成功</returns>
        public bool Update(string dictGuid, string dictCode, string dictText, string dictDesc, int seq)
        {
            try
            {
                string sql = string.Empty;
                sql = "Update InfoCodeDicts Set DictCode=@DictCode,DictText=@DictText,DictDesc=@DictDesc,Seq=@Seq Where DictGuid=@DictGuid";
                SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@DictGuid", dictGuid),
                    SqlHelper.NewSqlParameter("@DictCode", dictCode),
                    SqlHelper.NewSqlParameter("@DictText", dictText),
                    SqlHelper.NewSqlParameter("@DictDesc", dictDesc),
                    SqlHelper.NewSqlParameter("@Seq", seq));

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 获取字典表（数据集）
        /// </summary>
        /// <param name="cateGuid">索引Guid</param>
        /// <param name="parentDictGuid">父字典Guid</param>
        /// <returns></returns>
        public DataSet GetDictDs(string cateGuid, string parentDictGuid)
        {
            try
            {
                string sql = "Select * From InfoCodeDicts Where CateGuid=@CateGuid And ParentDictGuid=@ParentDictGuid Order by Seq Asc";
                return SqlHelper.ExecuteDataSet(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@CateGuid", cateGuid),
                    SqlHelper.NewSqlParameter("@ParentDictGuid", parentDictGuid));
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return null;
            }
        }

        /// <summary>
        /// 获取字典列表（数组）
        /// </summary>
        /// <param name="cateGuid">索引Guid</param>
        /// <param name="parentDictGuid">父字典Guid</param>
        /// <returns></returns>
        public List<Dict> GetDictList(string cateGuid, string parentDictGuid)
        {
            try
            {
                List<Dict> list = new List<Dict>();
                DataSet ds = this.GetDictDs(cateGuid, parentDictGuid);
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        list.Add(new Dict(row["DictGuid"].ToString(), row["ParentDictGuid"].ToString(), row["CateGuid"].ToString(), row["DictCode"].ToString(), row["DictText"].ToString(), row["DictDesc"].ToString(), int.Parse(row["Seq"].ToString())));
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return null;
            }
        }

        /// <summary>
        /// 判断是否有子字典
        /// </summary>
        /// <param name="dictGuid">字典ID</param>
        /// <returns></returns>
        public bool ExistChild(string dictGuid)
        {
            try
            {
                string sql = "Select DictGuid From InfoCodeDicts Where ParentDictGuid=@ParentDictGuid";
                DataSet ds = SqlHelper.ExecuteDataSet(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@ParentDictGuid", dictGuid));
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 获取多级字典的XML文本
        /// </summary>
        /// <param name="cateGuid">索引Guid</param>
        /// <returns></returns>
        public XmlDocument GetDictXmlDoc(string cateGuid)
        {
            XmlDocument xmldoc;
            XmlNode xmlnode;
            XmlElement xmlelement;

            xmldoc = new XmlDocument();
            xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            xmldoc.AppendChild(xmlnode);

            xmlelement = xmldoc.CreateElement("root");
            xmldoc.AppendChild(xmlelement);

            this.RecursionDict(ref xmldoc, ref xmlelement, cateGuid, "0");

            return xmldoc;
        }

        /// <summary>
        /// 递归多级字典
        /// </summary>
        /// <param name="xmldoc">XML文本</param>
        /// <param name="parentXmlElement">XML父节点</param>
        /// <param name="cateGuid">索引Guid</param>
        /// <param name="parentDictGuid">父字典Guid</param>
        private void RecursionDict(ref XmlDocument xmldoc, ref XmlElement parentXmlElement, string cateGuid, string parentDictGuid)
        {
            XmlElement xmlelement;
            List<Dict> list = this.GetDictList(cateGuid, parentDictGuid);
            foreach (Dict dict in list)
            {
                xmlelement = xmldoc.CreateElement("root_" + dict.DictGuid);
                xmlelement.SetAttribute("id", dict.DictGuid);
                if (dict.DictCode.Length > 0)
                {
                    xmlelement.SetAttribute("desc", dict.DictCode + "-" + dict.DictText);
                }
                else
                {
                    xmlelement.SetAttribute("desc", dict.DictText);
                }
                parentXmlElement.AppendChild(xmlelement);

                this.RecursionDict(ref xmldoc, ref xmlelement, cateGuid, dict.DictGuid);
            }
        }
    }
}
